<include file="Public/min-header" />
<link href="__PUBLIC__/plugins/daterangepicker/daterangepicker-bs3.css" rel="stylesheet" type="text/css" />
<script src="__PUBLIC__/plugins/daterangepicker/moment.min.js" type="text/javascript"></script>
<script src="__PUBLIC__/plugins/daterangepicker/daterangepicker.js" type="text/javascript"></script>
<div class="wrapper">
    <include file="Public/breadcrumb"/>
    <section class="content ">
        <!-- Main content -->
        <div class="container-fluid">
            <div class="pull-right">
                <a href="javascript:history.go(-1)" data-toggle="tooltip" title="" class="btn btn-default" data-original-title="返回"><i class="fa fa-reply"></i></a>
            </div>
            <div class="panel panel-default">
                <div class="panel-heading">
                    <h3 class="panel-title"><i class="fa fa-list"></i>兑换商品(不退不换)</h3>
                </div>
                <div class="panel-body ">   
                    <!--表单数据-->
                    <form method="post" id="handleposition" action="{:U('Admin/Promotion/exchangebuyHandle')}">                    
                        <!--通用信息-->
                    <div class="tab-content col-md-10">                 	  
                        <div class="tab-pane active" id="tab_tongyong">                           
                            <table class="table table-bordered">
                                <tbody>                                
                                <tr>
                                    <td>选择商品：</td>
                                    <td>
                                    	<div class="col-xs-9">
                             			<input type="text" id="goods_name" class="form-control" value="{$info.goods_name}">
                             			</div>
                             			<div class="col-xs-3">
                             			<input type="hidden" id="goods_id" name="goods_id" value="{$info.goods_id}">
                             			<input class="btn btn-primary" type="button" onclick="selectGoods()" value="选择商品">
                             			</div>
                                    </td>
                                    <td class="col-sm-4">请选择加入兑换的商品</td>
                                </tr>
                                <tr id="set_price">
                                    <td>兑换价格（积分）：</td>
                                    <td>
                                    	<div class="col-xs-4">
	                      					<input type="text" class="form-control" id="price" name="price" value="{$info.price}"  onpaste="this.value=this.value.replace(/[^\d.]/g,'')" onkeyup="this.value=this.value.replace(/[^\d.]/g,'')"/>
	                      					<input type="hidden" id="goods_price" name="goods_price" value="{$info.goods_price}">
                      					</div>
                      					<span id="price_html"></span>
                                    </td>
                                    <td class="col-sm-4">商品兑换价格(多规格商品时仅仅用于显示),注意兑换价格已经包含快递费用，下单时不收取任何现金</td>
                                </tr>
                                <tr id="set_total_num">
                                    <td>商品数量：</td>
                                    <td>
                      					<input type="text" class="form-control" id="goods_num" name="goods_num" value="{$info.goods_num}"  onpaste="this.value=this.value.replace(/[^\d]/g,'')" onkeyup="this.value=this.value.replace(/[^\d]/g,'')" onchange="checkSettings()" />
                                    </td>
                                    <td class="col-sm-4">请填写自然数作为参与兑换的商品数量(多规格商品时为所有规格的数量之和)</td>
                                </tr> 
                                <tr id="set_specs">
                                    <td>规格设置</td>
                                    <td>
                                        <table class="table table-bordered">
                                            <tr>
                                                <td>规格名称</td>
                                                <td>价格</td>
                                                <td>参与数量</td>
                                            </tr>
                                           
                                                <volist name="info.good_specs" id="vo">
                                                        <tr>
                                                            <td class="specs_key_name" title="{$vo.key_name}">
                                                                {$vo.key_name}
                                                                <input type="hidden" class="spec_name" name="spec[{$vo.key}][key_name]" value="{$vo.key_name}" placeholder="原价{$vo.key_name}">
                                                            </td>
                                                            <td>
                                                                <input type="number" class="spec_price" name="spec[{$vo.key}][price]" value="{$vo.price}" placeholder="原价{$vo.o_price}">
                                                            </td>
                                                            <td>
                                                                <input type="number" class="spec_num" name="spec[{$vo.key}][num]"  value="{$vo.num}" store="{$vo.store_count}" placeholder="库存{$vo.store_count}" onchange="checkSettings()">
                                                            </td>
                                                        </tr>
                                                </volist>
                                            
                                        </table>
                                    </td>
                                    <td class="col-sm-4">为每个规格设置兑换参数</td>
                                </tr>
                                <tr>
                                    <td>限购量/人：</td>
                                    <td>
                                        <input type="number" class="form-control" id="max_buy_num" name="max_buy_num" value="{$info.max_buy_num}"  onpaste="this.value=this.value.replace(/[^\d]/g,'')" onkeyup="this.value=this.value.replace(/[^\d]/g,'')"/>
                                    </td>
                                    <td class="col-sm-4">每个人最多兑换几件商品，0不限制</td>
                                </tr>   
                                </tbody> 
                                <tfoot>
                                	<tr>
                                	<td><input class="btn btn-default" type="reset" value="重置">
                                		<input type="hidden" name="act" value="{$act}">
                                		<input type="hidden" name="id" value="{$info.id}">
                                	</td>
                                	<td class="col-sm-4"></td>
                                	<td class="text-right"><input class="btn btn-primary" type="button" onclick="adsubmit()" value="保存"></td></tr>
                                </tfoot>                               
                                </table>
                        </div>                           
                    </div>              
			    	</form><!--表单数据-->
                </div>
            </div>
        </div>
    </section>
</div>
<style>

    <?php 
        if(!$info['good_specs']){
    ?>
    #set_specs{
        display: none;
    }
    <?php 
        } 
    ?>
    

    #set_specs input{
        width: 120px;
    }

    .specs_key_name{
        max-width: 120px;
        overflow: hidden;
        text-overflow:ellipsis;  
        -moz-text-overflow: ellipsis;
        overflow:hidden;
        white-space: nowrap;
    }

</style>

<script>

function adsubmit(){
	if($('#title').val() ==''){
		layer.msg('兑换标题不能为空');return;
	}
    if($('#goods_id').val() == 0){
		layer.msg('请选择商品');return;
	}
	if($('#price').val() == 0){
		layer.msg('兑换价格不能为空');return;
	}
	if($('#goods_num').val() == 0 ){
		layer.msg('商品数量不能为空');return;
	}
    var form = $("#handleposition")
    return $.ajax({
        url: form.attr('action'),
        data: form.serialize(),
        type: 'post',
        dataType: 'json',
        success: function(res){
            console.log(res)
            if( res.status < 1 )
            {
                return layer.msg(res.info||res.msg||'服务器错误')
            }else{
                layer.msg(res.info||res.msg||'操作成功')
            }
            if( res.url && res.url!='' )
            {
                return window.location.href = res.url
            }
            return window.location.href = document.URL
        },
        error: function(res)
        {
            layer.msg('服务器错误')
        }
    })

	// $('#handleposition').submit();
}

function selectGoods(){
    var url = "{:U('Promotion/search_goods',array('tpl'=>'select_goods'))}";
    layer.open({
        type: 2,
        title: '选择商品',
        shadeClose: true,
        shade: 0.2,
        area: ['75%', '75%'],
        content: url, 
    });
}


var goodsInfo = undefined;
// 选择商品
function call_back(goods_id,goods_name,store_count){
	

    goodsInfo = {
        goods_id: goods_id,
        goods_name: goods_name,
        store_count: store_count,
        specs: []
    };

    // 获取商品的规格信息
    $.ajax({
        url: "{:U('Goods/get_goods_specs')}",
        type: "POST",
        data:{
            goods_id: goods_id
        },
        dataType: "JSON",
        success: function(res)
        {
            console.log("商品规格信息",res);
            if( res && res.length > 0 )
            {
                goodsInfo.specs = res;
            }
            console.log("商品信息",goodsInfo);
            buildSpecsSettings();
        }
    })

	layer.closeAll('iframe');
}

// 验证多规格商品参数设置
function checkSettings()
{
    if( goodsInfo == undefined || goodsInfo.specs == undefined || goodsInfo.specs.length < 1 )
    return true;

    var total = $("#set_total_num").find("input");
    var specs = $("#set_specs").find(".spec_num");

    if( total.val() < 1 )
    {
        return layer.msg("参与兑换商品总数未设置");
    }
    var spec_total = 0;
    for( var i = 0; i < specs.length; i++ )
    {
        var num = parseInt( $(specs[i]).val()  ) || 0;
        if( num > parseInt( $(specs[i]).attr('store')) )
        {
            return layer.msg("当前规格库存不足");
        }
        spec_total = spec_total + num;
    }

    if( spec_total > total.val() )
    {
        return layer.msg("各规格总数和参与兑换商品总数设置不一致");
    }
}


// 构造多规格商品设置
// buildSpecsSettings();

function buildSpecsSettings()
{
    if(  goodsInfo )
    {
        $('#goods_id').val(goodsInfo.goods_id);
        $('#goods_name').val(goodsInfo.goods_name);
        $('#goods_num').val(goodsInfo.store_count);
    }

    var set_specs = $("#set_specs");
    var table = set_specs.find("table");
    if( goodsInfo == undefined || goodsInfo.specs == undefined || goodsInfo.specs.length<1 )
    {
        set_specs.hide();
        table.html('');
        return false;
    }

    var html = '<tr><td>规格名称</td><td>价格</td><td>参团数量</td></tr>';
    for(var i = 0; i < goodsInfo.specs.length;i++){
        var data =  goodsInfo.specs[i];
        html +='<tr>\
                    <td class="specs_key_name" title="'+data.key_name+'">'+data.key_name+'<input type="hidden" class="spec_name" name="spec['+data.key+'][key_name]" value="'+data.key_name+'" ></td>\
                    <td>\
                        <input type="number" class="spec_price" name="spec['+data.key+'][price]" placeholder="原价'+data.price+'">\
                    </td>\
                    <td>\
                        <input type="number" class="spec_num" name="spec['+data.key+'][num]" store="'+data.store_count+'" placeholder="库存'+data.store_count+'" onchange="checkSettings()">\
                    </td>\
                </tr>';
    }
    set_specs.show();
    table.html(html);
}
</script>
</body>
</html>